package com.example.backend.services.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.backend.common.Result;
import com.example.backend.mapper.BookMapper;
import com.example.backend.mapper.UserMapper;
import com.example.backend.pojo.Book;
import com.example.backend.pojo.User;
import com.example.backend.services.UserService;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    private BookMapper bookMapper;

    @Override
    public Result getUserList() {
        List<User> list = list();
        return Result.success("success").data("list", list);
    }

    @Override
    public User selectByUid(String uid) {
        return userMapper.selectById(uid);
    }

    @Override
    public Result login(String uid, String password) {
        User user = userMapper.selectById(uid);
        if (user == null) {
            return Result.error("用户不存在");
        }
        if (!user.getPassword().equals(password)) {
            return Result.error("密码错误");
        }
        return Result.success("登录成功").data("user", user);
    }

    @Override
    public Result changeRole(String uid) {
        User user = userMapper.selectById(uid);
        if (user == null) {
            return Result.error("用户不存在");
        }
        if (user.getRole().equals("user")) {
            user.setRole("admin");
        } else {
            user.setRole("user");
        }
        updateById(user);
        return Result.success("修改成功").data("user", user);
    }
    @Override
    public Result addUser(String password,String role) {
        int count= Math.toIntExact(userMapper.selectCount(new QueryWrapper<User>()));
        String uid = String.format("%04d", count+1);
        User user=new User(uid,password,role);
        userMapper.insert(user);
        return Result.success("添加成功");
    }
}